<?php 
$this->template->add_admin_js_lib('jquery-bonsai/jquery.bonsai.js');
$this->template->add_admin_js_lib('jquery-bonsai/jquery.qubit.js');
$this->template->add_admin_css_lib('../js/jquery-bonsai/jquery.bonsai.css');

$GLOBALS['selected'] = $selected;
$GLOBALS['menu_tree'] = $menu_tree;
$GLOBALS['checkExpanded'] = array_unique(checkExpanded($menu_tree));

function checkExpanded($menus, $result = array()) {
	global $menu_tree;
	global $selected;
	foreach($menus as $menu) {
		if (!empty($menu->child)) {
			foreach ($menu->child as $item) {
				if(in_array($item->term_id, $selected))
					$result[] = $menu->term_id;
			}
			$result = array_merge($result, checkExpanded($menu->child, $result));
		}
	}
	return $result;
}

function print_menu($menu) {
	global $selected;
	global $checkExpanded;
	$strSelected = (in_array($menu->term_id, $selected))?"data-checked='1'":"";
	$expanded = (in_array($menu->term_id, $checkExpanded))?"class='expanded'":"";
	echo "<li data-value='{$menu->term_id}' data-name='edit[term_id][]' $strSelected $expanded>{$menu->term_name}</i>";
	if (!empty($menu->child)) {
		echo '<ol>';
		foreach ($menu->child as $item) print_menu($item);
		echo '</ol>';
	}
	echo '</li>';
}
?>

<ol id='<?php echo @$list_id; ?>' data-name='edit[term_id][]'>
  <li class='expanded' data-value='0'>All
    <ol>
    	<?php if (isset($menu_tree) && $menu_tree) foreach ($menu_tree as $menu) print_menu($menu); ?>
    </ol>
  </li>
</ol>

<script type="text/javascript">

$(document).ready(function()
{
	$('#<?php echo @$list_id; ?>').bonsai({
	  	expandAll: false,
	  	checkboxes: true, // depends on jquery.qubit plugin
	  	createCheckboxes: true, // takes values from data-name and data-value, and data-name is inherited
	  	handleDuplicateCheckboxes: false // handleDuplicateCheckboxes: update any other checkboxes that have the same value
	});	
});
</script>
<style type="text/css" media="screen">
	#<?php echo @$list_id; ?> {
		max-height: 200px;
		overflow-y: scroll;
	}
</style>